package com.lianyu507.interceptor;

import com.lianyu507.util.ThreadLocalUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.lianyu507.util.UserContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class MyInterceptor implements HandlerInterceptor {

	Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("------preHandle------");
		//获取session
		//判断用户ID是否存在，不存在就跳转到登录界面
		///获取当前的请求uri
		String uri=request.getRequestURI();

		String[] strs=null;
		String uri1="";
		try {
			strs=uri.split("/");
			uri1=strs[2];
		}catch (Exception e){
			uri1="admin";
			e.printStackTrace();
		}

		if (uri1.equals("adminafter")) {

			   ////后台页面登录
			   if(UserContext.getCurrentManager()  == null){
				   response.sendRedirect(request.getContextPath()+"/adminafter/index");
				   return false;
			   }else{
				   //  session.setAttribute("SESSION_USER_NAME", session.getAttribute("SESSION_USER_NAME"));
				   return true;
			   }
		   }else if (uri1.equals("portal") || uri1.equals("html")){


			   String token=request.getHeader("token");
			   if(token == null){
				   request.getRequestDispatcher("/portal/login/needLogin").forward(request,response);
				   return false;
			   }
			   ThreadLocalUtil.setLoginSession(token);
			   if(UserContext.getCurrentUser() == null) {
					logger.info("------:跳转到login页面！");
					request.getRequestDispatcher("/portal/login/needLogin").forward(request,response);
					return false;
				} else {
					return true;
				}
		   }
		   ////没注册的uri，即是handmapping中没有的uri
		   else {
			   response.sendRedirect(request.getContextPath() + "/error/index");
				return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
						   ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}
}
